package com.lgx.common.util;

import org.apache.commons.lang.StringUtils;

import com.lgx.common.basic.dao.GeneralJdbcDao;


/**
 * 排序编码生成工具类
 * 
 * @author w10428
 *
 */
public class LayerOrderUtils {

	public final static String DEFAULT_LAYERORDER = "0000";
	
	public final static int DEFAULT_LEN = 4;
	
	/**
	 * 
	 * 
	 * @param tableName
	 * @param parentId
	 * @param dao
	 * @return
	 */
	public static String createLayerOrder(String tableName,String parentId,GeneralJdbcDao dao)
	{
		String sql = "select max(layerOrder) from " + tableName + " where parent = " + parentId;
		
		String data = dao.getJdbcTemplate().queryForObject(sql, String.class);
		
		if(StringUtils.isEmpty(data))
		{	
			sql  = "select layerOrder from " + tableName + " where id = " + parentId;
			data = dao.getJdbcTemplate().queryForObject(sql, String.class);
			data = data + "0001";
		}
		else 
		{
			int d = Integer.parseInt(data.substring(data.length()-DEFAULT_LEN));
			if(d < 9999)
			{
				d++;
				String t = d+"";
				String z = "";
				
				if(t.length() != DEFAULT_LEN)
				{
					for(int i=t.length();i<DEFAULT_LEN;i++)
					{
						z += "0";
					}
				}
				
				t = z + t;
				data = data.substring(0, data.length()-DEFAULT_LEN)+t;
			}else
			{
				data = data.substring(0, data.length()-DEFAULT_LEN)+d;
			}
		}
		return data;
	}
}
